package com.karl.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.karl.dao.ProductDao;
import com.karl.entity.Product;
import com.karl.util.Page;
import com.karl.util.PageDao;

@Component("productDao")
public class ProductDaoImpl implements ProductDao{

	private HibernateTemplate hibernateTemplate;
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	@Override
	public void save(Product p) {
		// TODO Auto-generated method stub
		hibernateTemplate.save(p);
	}
	@Override
	public List<Product> list(String key) {
//		String sql = "select * from product where (1=1) ";
//		StringBuffer buffer = new StringBuffer(sql);
//		List<Object> params = new ArrayList<Object>();
//		if (proname != null) {
//			buffer.append(" and proname like ? ");
//			params.add("%" + proname + "%");
//		}
//		buffer.append("limit ?,? ");
//		params.add(start);
//		params.add(end);
//		return (List<Product>)hibernateTemplate.find("from Product p where p.proname like '%" + key + "%'");
//		System.out.println(key=="");
//		System.out.println(key==null);
		String hql = "from Product p where (1=1) ";
		StringBuffer buffer = new StringBuffer(hql);
		if (key != null) {
			buffer.append(" and p.proname like '%" +key+"%'");
		}
//				+ "p.proname like '%" + key + "%'"
		return (List<Product>)hibernateTemplate.find(buffer.toString());
	}
	List<Product> products;

	
	
	PageDao pageDao;// = new PageDao(hibernateTemplate, 0, "Product");
	public PageDao getPageDao() {
		return pageDao;
	}
	@Resource
	public void setPageDao(PageDao pageDao) {
		this.pageDao = pageDao;
//		this.pageDao.init();
	}
	@Override
	public int count() {
		// TODO Auto-generated method stub
		return hibernateTemplate.find("from Product").size();
	}
	@Override
	public Page firstPage() {
		// TODO Auto-generated method stub
		return pageDao.getPage();
	}
	@Override
	public Page endPage() {
		// TODO Auto-generated method stub
		int i = pageDao.getPage().getTotalPage();
		pageDao.setPage(i);
		return pageDao.getPage();
	}
	@Override
	public Page prePage() {
		pageDao.setPrePage();
		
		return pageDao.getPage();
	}
	@Override
	public Page nextPage() {
		pageDao.init();
		pageDao.setNextPage();
		return pageDao.getPage();
	}
	@Override
	public Page selectPage(int i) {
		// TODO Auto-generated method stub
		pageDao.setPage(i);
		return pageDao.getPage();
	}
	

}
